#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2023/8/25 13:15
# @File           : crud.py
# @IDE            : PyCharm
# @desc           : 简要说明

from sqlalchemy.ext.asyncio import AsyncSession
from core.crud import DalBase
from . import models, schemas
from sqlalchemy import update, delete
import datetime
from utils.file.file_manage import FileManage
from utils.del_file import del_file
from fastapi import BackgroundTasks


class ImagesDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(ImagesDal, self).__init__()
        self.db = db
        self.model = models.VadminImages
        self.schema = schemas.ImagesSimpleOut

    async def delete_images(self, ids: list[int], v_soft: bool = False, **kwargs) -> None:
        if v_soft:
            await self.db.execute(
                update(self.model).where(self.model.id.in_(ids)).values(
                    delete_datetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    is_delete=True,
                    **kwargs
                )
            )
            await self.flush()
        else:
            # 先删除本地的文件
            images = await ImagesDal(self.db).get_datas(limit=0, id=("in", ids), v_return_objs=True)
            for image in images:
                del_file(image.image_url)
            # 再删除数据库
            await self.db.execute(delete(self.model).where(self.model.id.in_(ids)))
            await self.flush()


